<template>
  <div class="home">
    <!-- 轮播图 -->
    <div class="carousel">
      <el-carousel height="400px">
        <el-carousel-item v-for="(item, index) in carouselItems" :key="index">
          <img :src="item.imgUrl" alt="轮播图" class="carousel-img">
        </el-carousel-item>
      </el-carousel>
    </div>
    
    <!-- 分类导航 -->
    <div class="categories">
      <h2 class="section-title">商品分类</h2>
      <div class="category-list">
        <el-card 
          v-for="category in categories" 
          :key="category.id" 
          class="category-card"
          @click="handleCategoryClick(category.id)"
        >
          <div class="category-info">
            <h3>{{ category.name }}</h3>
            <p>{{ category.description || '点击查看更多' }}</p>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 热门商品 -->
    <div class="hot-products">
      <h2 class="section-title">热门商品</h2>
      <div class="product-list">
        <el-card 
          v-for="product in hotProducts" 
          :key="product.id" 
          class="product-card"
          @click="handleProductClick(product.id)"
        >
          <img :src="product.imageUrl" alt="商品图片" class="product-image">
          <div class="product-info">
            <h3 class="product-title">{{ product.name }}</h3>
            <p class="product-price">¥{{ formatPrice(product.price) }}</p>
            <el-button type="primary" size="small" class="add-to-cart-btn">
              加入购物车
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 新品推荐 -->
    <div class="new-products">
      <h2 class="section-title">新品推荐</h2>
      <div class="product-list">
        <el-card 
          v-for="product in products" 
          :key="product.id" 
          class="product-card"
          @click="handleProductClick(product.id)"
        >
          <img :src="product.imageUrl" alt="商品图片" class="product-image">
          <div class="product-info">
            <h3 class="product-title">{{ product.name }}</h3>
            <p class="product-price">¥{{ formatPrice(product.price) }}</p>
            <el-button type="primary" size="small" class="add-to-cart-btn">
              加入购物车
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { productService } from '../services/productService'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore } from '../store'
import { useUserStore } from '../store'

const router = useRouter()
const cartStore = useCartStore()

// 轮播图数据
const carouselItems = ref([
  { imgUrl: '/carousel1.jpg' },
  { imgUrl: '/carousel2.jpg' },
  { imgUrl: '/carousel3.jpg' }
])

// 分类数据
const categories = ref([])

// 热门商品数据
const hotProducts = ref([])

// 商品列表数据
const products = ref([])

// 加载分类数据
const loadCategories = async () => {
  try {
    const result = await productService.getCategories()
    categories.value = result || []
  } catch (error) {
    ElMessage.error('加载分类失败')
    console.error('加载分类失败:', error)
  }
}

// 加载热门商品数据
const loadHotProducts = async () => {
  console.log('开始加载热门商品数据...')
  try {
    const startTime = Date.now()
    const result = await productService.getHotProducts(8)
    const endTime = Date.now()
    console.log(`热门商品数据加载完成，耗时: ${endTime - startTime}ms`, result)
    
    hotProducts.value = result || []
    console.log('热门商品数据设置完成，商品数量:', hotProducts.value.length)
  } catch (error) {
    console.error('加载热门商品失败，错误详情:', error)
    console.error('错误状态码:', error.statusCode)
    console.error('错误消息:', error.customMessage)
    ElMessage.error('加载热门商品失败')
  }
}

// 加载商品列表数据
const loadProducts = async () => {
  try {
    const result = await productService.getProducts(1, 8)
    // 检查返回的数据结构
    if (Array.isArray(result)) {
      // 如果直接返回数组
      products.value = result
    } else if (result && result.products) {
      // 如果返回的是分页对象，包含products字段
      products.value = result.products || []
    } else if (result && result.data) {
      // 兼容旧的data字段格式
      products.value = result.data || []
    } else {
      products.value = []
    }
  } catch (error) {
    ElMessage.error('加载商品列表失败')
    console.error('加载商品列表失败:', error)
  }
}

// 处理分类点击
const handleCategoryClick = (categoryId) => {
  router.push(`/products?categoryId=${categoryId}`)
}

// 处理商品点击
const handleProductClick = (productId) => {
  router.push(`/product/${productId}`)
}

// 格式化价格显示
const formatPrice = (price) => {
  if (!price) return '0.00'
  
  // 如果价格是数字
  if (typeof price === 'number') {
    return price.toFixed(2)
  }
  
  // 如果价格是字符串，尝试转换为数字
  if (typeof price === 'string') {
    const num = parseFloat(price)
    if (!isNaN(num)) {
      return num.toFixed(2)
    }
    return price
  }
  
  // 如果价格是对象，尝试获取parsedValue或value
  if (typeof price === 'object') {
    if (price.parsedValue !== undefined) {
      return price.parsedValue.toFixed(2)
    }
    if (price.value !== undefined) {
      return price.value.toFixed(2)
    }
  }
  
  return '0.00'
}

// 页面加载时初始化数据
onMounted(() => {
  // 直接加载所有数据，不需要检查登录状态
  // 分类API应该是公开的，不需要认证
  loadCategories()
  loadHotProducts()
  loadProducts()
})
</script>

<style scoped>
.home {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.carousel {
  margin-bottom: 40px;
}

.carousel-img {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.categories {
  margin-bottom: 40px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.category-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.category-card {
  width: 200px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.category-info {
  text-align: center;
}

.hot-products,
.new-products {
  margin-bottom: 40px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  height: 350px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
}

.product-info {
  padding: 10px;
}

.product-title {
  font-size: 16px;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 10px;
}

.add-to-cart-btn {
  width: 100%;
}
</style>